//
//  CoreDataStack.m
//  SpriteCoreData
//
//  Created by ClassWizard on 15/8/6.
//  Copyright (c) 2015年 Apportable. All rights reserved.
//

#import "CoreDataStack.h"

@implementation CoreDataStack

@synthesize context;
@synthesize model;
@synthesize psc;
@synthesize store;

- (instancetype)init {
    self = [super init];
    if (self) {
        //1
        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"SpriteCoreData" withExtension:@"momd"];
        model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
        
        //2
        psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
        //3
        context = [[NSManagedObjectContext alloc] init];
        [context setPersistentStoreCoordinator:psc];
        
        //4
        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"SpriteCoreData.sqlite"];
        
        //options
        NSError *error = nil;
        store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
        
        if (store == nil) {
            abort();
        }
    }
    return self;

}

static CoreDataStack * sharedCoreDataStack = nil;
+ (CoreDataStack *)sharedCoreDataStack {
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedCoreDataStack = [[self alloc] init];
    });
    return sharedCoreDataStack;
}



- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.finemanager.HelloCoreData" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (void)saveContext {
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error])
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

}

@end
